<template>
  <div class="work-order-container">
    <!-- 工单管理主表 -->
    <div class="work-order-section">
      <div class="section-header">
        <h3>工单</h3>
      </div>
      
      <!-- 搜索和操作栏 -->
      <div class="search-action-bar">
        <div class="search-area">
          <el-input
            v-model="searchForm.orderNo"
            placeholder="工单编号"
            clearable
            style="width: 200px; margin-right: 10px;"
          />
          <el-button type="primary" @click="handleSearch">Q查询</el-button>
        </div>
        
        <div class="action-buttons">
          <el-button type="success" @click="handleAdd">+新建</el-button>
          <el-button type="warning" @click="handleBatchStart">◎开始</el-button>
          <el-button type="warning" @click="handleBatchCancel">取消</el-button>
          <el-button type="warning" @click="handleBatchEnd">结束</el-button>
          <el-button type="warning" @click="handleBatchRecall">《撤回</el-button>
        </div>
      </div>

      <!-- 工单表格 -->
      <div class="table-container">
        <el-table
          :data="workOrderList"
          @selection-change="handleSelectionChange"
          v-loading="loading"
          style="width: 100%"
          border
          stripe
          highlight-current-row
        >
          <el-table-column type="selection" width="50" />
          <el-table-column prop="orderNo" label="工单编号" sortable width="180">
            <template #default="scope">
              <el-link type="primary" @click="handleViewDetail(scope.row)">
                {{ scope.row.orderNo }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column prop="product" label="产品" width="120">
            <template #default="scope">
              <el-link type="primary" @click="handleViewProduct(scope.row)">
                {{ scope.row.product }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column prop="productCode" label="产品编号" width="180" />
          <el-table-column prop="productName" label="产品名称" width="150" />
          <el-table-column prop="productSpec" label="产品规格" width="120" />
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column prop="relatedDocuments" label="关联单据" width="150">
            <template #default="scope">
              <el-link type="primary" @click="handleViewRelatedDoc(scope.row)">
                {{ scope.row.relatedDocuments }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="plannedStartTime" label="计划开始时间" width="180">
            <template #default="scope">
              {{ formatDateTime(scope.row.plannedStartTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="plannedEndTime" label="计划结束时间" width="180">
            <template #default="scope">
              {{ formatDateTime(scope.row.plannedEndTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="plannedQty" label="计划数" width="100" />
          <el-table-column prop="actualQty" label="实际数" width="100" />
          <el-table-column prop="goodQty" label="良品数" width="100" />
          <el-table-column prop="badQty" label="不良品数" width="100" />
          <el-table-column prop="workTimeMinutes" label="报工时长" width="120" />
          <el-table-column prop="progress" label="生产进度" width="200">
            <template #default="scope">
              <div class="progress-display">
                <el-icon class="progress-icon"><CircleCheck /></el-icon>
                <span>{{ scope.row.progress }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="startTime" label="实际开始时间" width="180">
            <template #default="scope">
              {{ formatDateTime(scope.row.startTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="endTime" label="实际结束时间" width="180">
            <template #default="scope">
              {{ formatDateTime(scope.row.endTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" width="150" />
          <el-table-column prop="createTime" label="创建时间" width="180">
            <template #default="scope">
              {{ formatDateTime(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="creator" label="创建人" width="120" />
          <el-table-column prop="modifier" label="修改人" width="120" />
          <el-table-column prop="modifyTime" label="修改时间" width="180">
            <template #default="scope">
              {{ formatDateTime(scope.row.modifyTime) }}
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="pagination.pageIndex"
          :page-size="pagination.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="pagination.totalCount"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 详情抽屉 -->
      <el-drawer
        v-model="detailDrawerVisible"
        title="工单详情"
        size="50%"
        :with-header="true"
      >
        <div v-if="detailData" class="detail-content">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="工单编号">{{ detailData.orderNo }}</el-descriptions-item>
            <el-descriptions-item label="状态">{{ detailData.status }}</el-descriptions-item>
            <el-descriptions-item label="产品">{{ detailData.product }}</el-descriptions-item>
            <el-descriptions-item label="产品名称">{{ detailData.productName }}</el-descriptions-item>
            <el-descriptions-item label="产品规格">{{ detailData.productSpec }}</el-descriptions-item>
            <el-descriptions-item label="单位">{{ detailData.unit }}</el-descriptions-item>
            <el-descriptions-item label="计划开始">{{ formatDateTime(detailData.plannedStartTime as any) }}</el-descriptions-item>
            <el-descriptions-item label="计划结束">{{ formatDateTime(detailData.plannedEndTime as any) }}</el-descriptions-item>
            <el-descriptions-item label="计划数">{{ detailData.plannedQty }}</el-descriptions-item>
            <el-descriptions-item label="实际数">{{ detailData.actualQty }}</el-descriptions-item>
            <el-descriptions-item label="良品数">{{ detailData.goodQty }}</el-descriptions-item>
            <el-descriptions-item label="不良数">{{ detailData.badQty }}</el-descriptions-item>
            <el-descriptions-item label="报工人">{{ detailData.producer }}</el-descriptions-item>
            <el-descriptions-item label="工时(分钟)">{{ detailData.workTimeMinutes }}</el-descriptions-item>
            <el-descriptions-item label="进度">{{ detailData.progress }}</el-descriptions-item>
            <el-descriptions-item label="开始时间">{{ formatDateTime(detailData.startTime as any) }}</el-descriptions-item>
            <el-descriptions-item label="结束时间">{{ formatDateTime(detailData.endTime as any) }}</el-descriptions-item>
            <el-descriptions-item label="审批状态">{{ detailData.approveStatus }}</el-descriptions-item>
            <el-descriptions-item label="审批人">{{ detailData.approver }}</el-descriptions-item>
            <el-descriptions-item label="审批时间">{{ formatDateTime(detailData.approveTime as any) }}</el-descriptions-item>
            <el-descriptions-item label="关联单据">{{ detailData.relatedDocuments }}</el-descriptions-item>
            <el-descriptions-item label="备注">{{ detailData.remarks }}</el-descriptions-item>
            <el-descriptions-item label="创建人">{{ detailData.creator }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ formatDateTime(detailData.createTime as any) }}</el-descriptions-item>
            <el-descriptions-item label="修改人">{{ detailData.modifier }}</el-descriptions-item>
            <el-descriptions-item label="修改时间">{{ formatDateTime(detailData.modifyTime as any) }}</el-descriptions-item>
          </el-descriptions>

          <!-- 工序详情 -->
          <div class="process-detail" v-if="detailData && (detailData.workProcessDetail || detailData.processCode || detailData.workPermission || detailData.taskName)">
            <h4>工序详情</h4>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="工序名称">{{ detailData.workProcessDetail?.processName || detailData.taskName || '-' }}</el-descriptions-item>
              <el-descriptions-item label="工序编号">{{ detailData.workProcessDetail?.processCode || detailData.processCode || '-' }}</el-descriptions-item>
              <el-descriptions-item label="报工权限">{{ detailData.workProcessDetail?.workPermission || detailData.workPermission || '-' }}</el-descriptions-item>
              <el-descriptions-item label="工时比例">{{ detailData.workProcessDetail?.workRatio ?? '-' }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </div>
      </el-drawer>
    </div>



    <!-- 新建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="1200px"
      :before-close="handleDialogClose"
      top="5vh"
    >
      <div class="dialog-content">
        <!-- 基本信息 -->
        <div class="basic-info-section">
          <h4>基本信息</h4>
          <el-form :model="formData" label-width="120px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="工单编号:">
                  <el-input 
                    v-model="formData.orderNo" 
                    placeholder="请输入,忽略将自动生成"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="*产品:">
                  <div style="display: flex; gap: 10px;">
                    <el-select 
                      v-model="formData.productId" 
                      placeholder="请选择产品" 
                      style="flex: 1;"
                      @change="handleProductChange"
                      filterable
                    >
                      <el-option 
                        v-for="product in productList" 
                        :key="product.productId" 
                        :label="`${product.productCode} - ${product.productName}`" 
                        :value="product.productId" 
                      />
                    </el-select>
                    <el-button type="primary" size="small" @click="handleAdvancedProductSelect">
                      <el-icon><Search /></el-icon>
                      高级选择
                    </el-button>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="*产品名称:">
                  <el-input v-model="formData.productName" placeholder="请先选择产品" :disabled="productFieldsDisabled" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="产品规格:">
                  <el-input v-model="formData.productSpec" placeholder="请先选择产品" :disabled="productFieldsDisabled" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="*产品编号:">
                  <el-input v-model="formData.productCode" placeholder="请先选择产品" :disabled="productFieldsDisabled" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="*单位:">
                  <el-input v-model="formData.unit" placeholder="请先选择产品" :disabled="productFieldsDisabled" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="*计划数:">
                  <el-input-number v-model="formData.plannedQty" :min="0" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="*计划开始时间:">
                  <el-date-picker
                    v-model="formData.plannedStartTime"
                    type="datetime"
                    placeholder="选择计划开始时间"
                    style="width: 100%"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="*计划结束时间:">
                  <el-date-picker
                    v-model="formData.plannedEndTime"
                    type="datetime"
                    placeholder="选择计划结束时间"
                    style="width: 100%"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="*状态:">
                  <el-radio-group v-model="formData.status" disabled>
                    <el-radio label="未开始">未开始</el-radio>
                    <el-radio label="进行中">进行中</el-radio>
                    <el-radio label="已完成">已完成</el-radio>
                    <el-radio label="已撤回">已撤回</el-radio>
                    <el-radio label="已取消">已取消</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="备注:">
                  <el-input
                    v-model="formData.remarks"
                    type="textarea"
                    :rows="3"
                    placeholder="备注"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>

        <!-- 任务部分 -->
        <div class="tasks-section">
          <h4>任务</h4>
          
          <!-- 任务操作按钮 -->
          <div class="task-actions">
            <el-button type="primary" size="small" @click="handleAddWorkProcess">
              <el-icon><Plus /></el-icon>
              +从工序中添加
            </el-button>
            <el-button type="danger" size="small" @click="handleDeleteTaskRows">
              <el-icon><Delete /></el-icon>
              删除行
            </el-button>
            <el-button type="info" size="small" @click="handleImportTasks">
              <el-icon><Upload /></el-icon>
              导入
            </el-button>
            <el-button type="warning" size="small" @click="handleRefreshTasks">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>

          <!-- 任务表格 -->
          <el-table
            :data="taskList"
            @selection-change="handleTaskSelectionChange"
            style="width: 100%"
            border
            stripe
            height="300"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="taskCode" label="工序编号" min-width="180" sortable />
            <el-table-column prop="taskName" label="工序名称" min-width="150" sortable>
              <template #default="scope">
                <el-select 
                  v-model="scope.row.taskName" 
                  placeholder="请选择工序"
                  style="width: 100%"
                  @change="handleTaskChange(scope.$index, $event)"
                >
                  <el-option 
                    v-for="process in workProcessList" 
                    :key="process.workProcessId" 
                    :label="process.processName" 
                    :value="process.processName" 
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="reportPermission" label="报工权限" min-width="200">
              <template #default="{ row }">
                <el-tooltip v-if="row.reportPermission && row.reportPermission.length > 20" :content="row.reportPermission" placement="top">
                  <span>{{ row.reportPermission.substring(0, 20) }}...</span>
                </el-tooltip>
                <span v-else>{{ row.reportPermission || '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="reportQtyRatio" label="报工数配比" width="120" />
            <el-table-column prop="defectiveItemList" label="不良品项列表" min-width="300">
              <template #default="{ row }">
                <el-tooltip v-if="row.defectiveItemList && row.defectiveItemList.length > 50" :content="row.defectiveItemList" placement="top">
                  <span>{{ row.defectiveItemList.substring(0, 50) }}...</span>
                </el-tooltip>
                <span v-else>{{ row.defectiveItemList || '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180" sortable>
              <template #default="{ row }">
                {{ formatDateTime(row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="creator" label="创建人" width="120" />
            <el-table-column prop="modifier" label="修改人" width="120" />
            <el-table-column prop="modifyTime" label="修改时间" width="180" sortable>
              <template #default="{ row }">
                {{ formatDateTime(row.modifyTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="plannedStartTime" label="计划开始时间" width="180" sortable>
              <template #default="scope">
                <el-date-picker
                  v-model="scope.row.plannedStartTime"
                  type="datetime"
                  placeholder="选择时间"
                  style="width: 100%"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </template>
            </el-table-column>
          </el-table>

          <!-- 任务分页 -->
          <div class="task-pagination">
            <el-pagination
              :current-page="taskPagination.pageIndex"
              :page-size="taskPagination.pageSize"
              :page-sizes="[50, 100, 200]"
              :total="taskPagination.totalCount"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleTaskSizeChange"
              @current-change="handleTaskCurrentChange"
            />
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button type="danger" @click="handleSave">
            <el-icon><Check /></el-icon>
            保存
          </el-button>
          <el-button type="primary" @click="handleDialogClose">
            <el-icon><Close /></el-icon>
            关闭
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 产品高级选择弹出框 -->
    <el-dialog
      v-model="productSelectDialogVisible"
      title="选择数据"
      width="1200px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="product-select-container">
        <!-- 搜索区域 -->
        <div class="search-section">
          <el-form :model="productSearchForm" inline>
            <el-form-item label="产品编码">
              <el-input
                v-model="productSearchForm.productCode"
                placeholder="请输入产品编码"
                style="width: 200px;"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleProductSearch">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 产品表格 -->
        <div class="table-section">
          <el-table
            :data="productSelectList"
            @selection-change="handleProductSelectionChange"
            v-loading="productSelectLoading"
            style="width: 100%"
            border
            stripe
            highlight-current-row
          >
            <el-table-column type="selection" width="50" />
            <el-table-column prop="productCode" label="产品编号" width="180" />
            <el-table-column prop="productName" label="产品名称" width="150" />
            <el-table-column prop="inventoryUnit" label="库存单位" width="100" />
            <el-table-column prop="productSpec" label="产品规格" width="120" />
            <el-table-column prop="productAttribute" label="产品属性" width="100" />
            <el-table-column prop="processRouteId" label="工艺路线" width="120" />
            <el-table-column prop="maxInventory" label="最大库存" width="100" />
            <el-table-column prop="minInventory" label="最小库存" width="100" />
            <el-table-column prop="safetyInventory" label="安全库存" width="100" />
            <el-table-column prop="currentInventory" label="当前库存" width="100" />
          </el-table>

          <!-- 分页 -->
          <div class="pagination-section">
            <el-pagination
              :current-page="productSelectPagination.pageIndex"
              :page-size="productSelectPagination.pageSize"
              :page-sizes="[10, 20, 30, 50]"
              :total="productSelectPagination.totalCount"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleProductSelectSizeChange"
              @current-change="handleProductSelectCurrentChange"
            />
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleAddSelectedProducts">
            <el-icon><Plus /></el-icon>
            +添加选择的数据
          </el-button>
          <el-button @click="handleProductSelectClose">
            <el-icon><Close /></el-icon>
            ×关闭
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 工序选择弹出框 -->
    <el-dialog
      v-model="workProcessSelectDialogVisible"
      title="选择工序"
      width="1200px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="work-process-select-container">
        <!-- 搜索区域 -->
        <div class="search-section">
          <el-form :model="workProcessSearchForm" inline>
            <el-form-item label="工序编码">
              <el-input
                v-model="workProcessSearchForm.processCode"
                placeholder="请输入工序编码"
                style="width: 200px;"
              />
            </el-form-item>
            <el-form-item label="工序名称">
              <el-input
                v-model="workProcessSearchForm.processName"
                placeholder="请输入工序名称"
                style="width: 200px;"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleWorkProcessSearch">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
              <el-button @click="handleWorkProcessReset">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 工序表格 -->
        <div class="table-section">
          <el-table
            :data="workProcessSelectList"
            @selection-change="handleWorkProcessSelectionChange"
            v-loading="workProcessSelectLoading"
            style="width: 100%"
            border
            stripe
            highlight-current-row
          >
            <el-table-column type="selection" width="50" />
            <el-table-column prop="processCode" label="工序编号" width="150" />
            <el-table-column prop="processName" label="工序名称" width="200" />
            <el-table-column prop="workRatio" label="工时比例" width="100" />
            <el-table-column prop="workPermission" label="工作权限" width="150" />
            <el-table-column prop="createTime" label="创建时间" width="180">
              <template #default="scope">
                {{ formatDateTime(scope.row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="creator" label="创建人" width="120" />
          </el-table>

          <!-- 分页 -->
          <div class="pagination-section">
            <el-pagination
              :current-page="workProcessSelectPagination.pageIndex"
              :page-size="workProcessSelectPagination.pageSize"
              :page-sizes="[10, 20, 30, 50]"
              :total="workProcessSelectPagination.totalCount"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleWorkProcessSelectSizeChange"
              @current-change="handleWorkProcessSelectCurrentChange"
            />
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleAddSelectedWorkProcesses">
            <el-icon><Plus /></el-icon>
            +添加选择的数据
          </el-button>
          <el-button @click="handleWorkProcessSelectClose">
            <el-icon><Close /></el-icon>
            ×关闭
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { CircleCheck, Search, Plus, Delete, Upload, Refresh, Check, Close } from '@element-plus/icons-vue'
import {
  getWorkOrders,
  getWorkOrderById,
  createWorkOrder,
  updateWorkOrder,
  deleteWorkOrder,
  startWorkOrder,
  endWorkOrder,
  cancelWorkOrder,
  recallWorkOrder,
  getProducts,
  getWorkProcesses,
  getProductById,
  getWorkProcessesByProductId,
  type WorkOrder,
  type SearchParams,
  type Product,
  type WorkProcess
} from '@/api/workOrder'

// 任务数据类型
interface Task {
  taskId?: number
  taskName: string
  taskCode: string
  defectiveItemList?: string
  reportPermission?: string
  reportQtyRatio: number
  plannedStartTime?: string
  createTime?: string
  creator?: string
  modifier?: string
  modifyTime?: string
}

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const selectedRows = ref<WorkOrder[]>([])
const taskList = ref<Task[]>([])
const selectedTaskRows = ref<Task[]>([])
const productList = ref<Product[]>([])
const workProcessList = ref<WorkProcess[]>([])

// 产品选择弹出框相关数据
const productSelectDialogVisible = ref(false)
const productSelectLoading = ref(false)
const productSelectList = ref<Product[]>([])
const selectedProductRows = ref<Product[]>([])

// 产品搜索表单
const productSearchForm = reactive({
  productCode: ''
})

// 产品选择分页数据
const productSelectPagination = reactive({
  pageIndex: 1,
  pageSize: 30,
  totalCount: 0
})

// 工序选择弹出框相关数据
const workProcessSelectDialogVisible = ref(false)
const workProcessSelectLoading = ref(false)
const workProcessSelectList = ref<WorkProcess[]>([])
const selectedWorkProcessRows = ref<WorkProcess[]>([])

// 工序搜索表单
const workProcessSearchForm = reactive({
  processCode: '',
  processName: ''
})

// 工序选择分页数据
const workProcessSelectPagination = reactive({
  pageIndex: 1,
  pageSize: 30,
  totalCount: 0
})

// 产品字段状态控制
const productFieldsDisabled = ref(true)

// 列表数据
const workOrderList = ref<WorkOrder[]>([])

// 搜索表单
const searchForm = reactive<SearchParams>({
  orderNo: ''
})



// 分页数据
const pagination = reactive({
  pageIndex: 1,
  pageSize: 30,
  totalCount: 0
})

// 任务分页数据
const taskPagination = reactive({
  pageIndex: 1,
  pageSize: 100,
  totalCount: 0
})

// 表单数据
const formData = reactive<Partial<WorkOrder> & { productId?: number }>({
  orderNo: '',
  productId: undefined,
  product: '',
  productCode: '',
  productName: '',
  productSpec: '',
  unit: '',
  plannedStartTime: '',
  plannedEndTime: '',
  plannedQty: 1,  // 改为1，满足后端验证要求
  actualQty: 0,
  goodQty: 0,
  badQty: 0,
  workTimeMinutes: 480,
  producer: '',
  workCount: 0,
  progress: '0%',
  startTime: '',
  endTime: '',
  workTimeHours: 8.0,
  standardEfficiency: 0.0,
  actualEfficiency: 0.0,
  approveStatus: '待审批',
  approver: '',
  approveTime: '',
  modifier: '',
  relatedDocuments: '',
  remarks: '',
  status: '未开始',
  creator: 'admin'
})

// 详情抽屉状态
const detailDrawerVisible = ref(false)
const detailData = ref<WorkOrder | null>(null)

// 获取工单列表
const fetchWorkOrders = async () => {
  try {
    loading.value = true
    
    const params: SearchParams = {
      ...searchForm,
      pageIndex: pagination.pageIndex,
      pageSize: pagination.pageSize
    }
    
    const response = await getWorkOrders(params)
    if (response.data.code === 200) {
      workOrderList.value = response.data.data.items
      pagination.totalCount = response.data.data.totalCount
    } else {
      ElMessage.error(response.data.msg || '获取数据失败')
    }
  } catch (error) {
    console.error('获取工单列表失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.pageIndex = 1
  fetchWorkOrders()
}



// 新建
const handleAdd = () => {
  dialogTitle.value = '新建工单'
  
  // 生成工单编号
  const now = new Date()
  const orderNo = `WO${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`
  
  Object.assign(formData, {
    orderNo: orderNo,
    productId: undefined,
    product: '',
    productCode: '',
    productName: '',
    productSpec: '',
    unit: '',
    plannedStartTime: '',
    plannedEndTime: '',
    plannedQty: 1,  // 改为1，满足后端验证要求
    actualQty: 0,
    goodQty: 0,
    badQty: 0,
    workTimeMinutes: 480,
    producer: '',
    workCount: 0,
    progress: '0%',
    startTime: '',
    endTime: '',
    workTimeHours: 8.0,
    standardEfficiency: 0.0,
    actualEfficiency: 0.0,
    approveStatus: '待审批',
    approver: '',
    approveTime: '',
    modifier: '',
    relatedDocuments: '',
    remarks: '',
    status: '未开始',
    creator: 'admin'
  })
  
  // 重置产品字段状态为禁用
  productFieldsDisabled.value = true
  
  dialogVisible.value = true
}

// 表格选择变化
const handleSelectionChange = (selection: WorkOrder[]) => {
  selectedRows.value = selection
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.pageIndex = 1
  fetchWorkOrders()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.pageIndex = page
  fetchWorkOrders()
}

// 对话框关闭
const handleDialogClose = () => {
  dialogVisible.value = false
}

// 保存
const handleSave = async () => {
  try {
    // 验证必填字段
    if (!formData.productName || formData.productName.trim() === '') {
      ElMessage.error('请选择产品')
      return
    }
    
    if (!formData.plannedQty || formData.plannedQty <= 0) {
      ElMessage.error('请输入有效的计划数量')
      return
    }
    
    // 准备保存数据，确保所有必需字段都有值
    const saveData = {
      ...formData,
      // 设置默认值
      productName: formData.productName?.trim() || '',
      plannedQty: formData.plannedQty || 1,
      actualQty: formData.actualQty ?? 0,
      goodQty: formData.goodQty ?? 0,
      badQty: formData.badQty ?? 0,
      workTimeMinutes: formData.workTimeMinutes ?? 480,
      producer: formData.producer || formData.creator || 'admin',
      workCount: formData.workCount ?? 0,
      progress: formData.progress || '0%',
      workTimeHours: formData.workTimeHours ?? 8.0,
      standardEfficiency: formData.standardEfficiency ?? 0.0,
      actualEfficiency: formData.actualEfficiency ?? 0.0,
      approveStatus: formData.approveStatus || '待审批',
      approver: formData.approver || '',
      approveTime: formData.approveTime || '',
      modifier: formData.modifier || formData.creator || 'admin',
      creator: formData.creator || 'admin'
    }
    
    // 格式化日期字段为ISO格式
    if (saveData.plannedStartTime) {
      saveData.plannedStartTime = new Date(saveData.plannedStartTime).toISOString()
    }
    if (saveData.plannedEndTime) {
      saveData.plannedEndTime = new Date(saveData.plannedEndTime).toISOString()
    }
    
    // 对于空字符串的日期字段，设置为 undefined，让后端使用默认值
    if (!saveData.startTime || saveData.startTime === '') {
      (saveData as any).startTime = undefined
    } else {
      saveData.startTime = new Date(saveData.startTime).toISOString()
    }
    
    if (!saveData.endTime || saveData.endTime === '') {
      (saveData as any).endTime = undefined
    } else {
      saveData.endTime = new Date(saveData.endTime).toISOString()
    }
    
    if (!saveData.approveTime || saveData.approveTime === '') {
      (saveData as any).approveTime = undefined
    } else {
      saveData.approveTime = new Date(saveData.approveTime).toISOString()
    }
    
    const response = await createWorkOrder(saveData)
    if (response.data.code === 200) {
      ElMessage.success('保存成功')
      dialogVisible.value = false
      fetchWorkOrders()
    } else {
      ElMessage.error(response.data.msg || '保存失败')
    }
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}



// 批量开始
const handleBatchStart = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要开始的工单')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要开始选中的 ${selectedRows.value.length} 个工单吗？`,
      '确认开始',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const promises = selectedRows.value.map(row => startWorkOrder(row.workOrderId))
    await Promise.all(promises)
    ElMessage.success('开始成功')
    fetchWorkOrders()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('开始失败:', error)
      ElMessage.error('开始失败')
    }
  }
}

// 批量取消
const handleBatchCancel = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要取消的工单')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要取消选中的 ${selectedRows.value.length} 个工单吗？`,
      '确认取消',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const promises = selectedRows.value.map(row => cancelWorkOrder(row.workOrderId))
    await Promise.all(promises)
    ElMessage.success('取消成功')
    fetchWorkOrders()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消失败:', error)
      ElMessage.error('取消失败')
    }
  }
}

// 批量结束
const handleBatchEnd = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要结束的工单')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要结束选中的 ${selectedRows.value.length} 个工单吗？`,
      '确认结束',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const promises = selectedRows.value.map(row => endWorkOrder(row.workOrderId))
    await Promise.all(promises)
    ElMessage.success('结束成功')
    fetchWorkOrders()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('结束失败:', error)
      ElMessage.error('结束失败')
    }
  }
}

// 批量撤回
const handleBatchRecall = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要撤回的工单')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要撤回选中的 ${selectedRows.value.length} 个工单吗？`,
      '确认撤回',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const promises = selectedRows.value.map(row => recallWorkOrder(row.workOrderId))
    await Promise.all(promises)
    ElMessage.success('撤回成功')
    fetchWorkOrders()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('撤回失败:', error)
      ElMessage.error('撤回失败')
    }
  }
}



// 查看详情（调用详情接口，带回工序详情）
const handleViewDetail = async (row: WorkOrder) => {
  try {
    const resp = await getWorkOrderById(row.workOrderId)
    if (resp.data.code === 200 && resp.data.data) {
      detailData.value = resp.data.data
    } else {
      detailData.value = row
    }
  } catch (e) {
    detailData.value = row
  }
  detailDrawerVisible.value = true
}

// 查看产品
const handleViewProduct = (row: WorkOrder) => {
  ElMessage.info(`查看产品: ${row.product}`)
}

// 查看关联单据
const handleViewRelatedDoc = (row: WorkOrder) => {
  ElMessage.info(`查看关联单据: ${row.relatedDocuments}`)
}

// 获取状态类型
const getStatusType = (status: string) => {
  switch (status) {
    case '未开':
      return 'info'
    case '进行中':
      return 'warning'
    case '已完成':
      return 'success'
    case '已取消':
      return 'danger'
    default:
      return 'info'
  }
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 任务相关方法
const handleAddTask = () => {
  ElMessage.info('从工序中添加功能待实现')
}

const handleDeleteTaskRows = () => {
  if (selectedTaskRows.value.length === 0) {
    ElMessage.warning('请选择要删除的任务')
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedTaskRows.value.length} 个任务吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const selectedIds = selectedTaskRows.value.map(row => row.taskId)
    taskList.value = taskList.value.filter(
      item => !selectedIds.includes(item.taskId)
    )
    taskPagination.totalCount = taskList.value.length
    ElMessage.success('删除成功')
  })
}

const handleImportTasks = () => {
  ElMessage.info('导入功能待实现')
}

const handleRefreshTasks = () => {
  ElMessage.success('刷新成功')
}

const handleTaskSelectionChange = (selection: Task[]) => {
  selectedTaskRows.value = selection
}

const handleTaskSizeChange = (size: number) => {
  taskPagination.pageSize = size
  taskPagination.pageIndex = 1
  // 这里可以重新加载任务数据
}

const handleTaskCurrentChange = (page: number) => {
  taskPagination.pageIndex = page
  // 这里可以重新加载任务数据
}

// 获取产品列表
const fetchProducts = async () => {
  try {
    const response = await getProducts()
    if (response.data.code === 200) {
      productList.value = response.data.data || []
    }
  } catch (error) {
    console.error('获取产品列表失败:', error)
  }
}

// 获取工序列表
const fetchWorkProcesses = async () => {
  try {
    const response = await getWorkProcesses()
    if (response.data.code === 200) {
      workProcessList.value = response.data.data || []
    }
  } catch (error) {
    console.error('获取工序列表失败:', error)
  }
}

// 根据产品ID获取相关工序
const fetchWorkProcessesByProductId = async (productId: number) => {
  try {
    const response = await getWorkProcessesByProductId(productId)
    if (response.data.code === 200) {
      workProcessList.value = response.data.data || []
    }
  } catch (error) {
    console.error('获取产品相关工序失败:', error)
  }
}

// 产品选择变化处理
const handleProductChange = async (productId: number) => {
  if (productId) {
    try {
      const response = await getProductById(productId)
      if (response.data.code === 200 && response.data.data) {
        const product = response.data.data
        formData.product = product.productName
        formData.productCode = product.productCode
        formData.productName = product.productName
        formData.productSpec = product.productSpec
        formData.unit = product.inventoryUnit
      }
      // 获取产品相关工序
      await fetchWorkProcessesByProductId(productId)
    } catch (error) {
      console.error('获取产品信息失败:', error)
    }
  }
}

// 任务变化处理
const handleTaskChange = (index: number, taskName: string) => {
  const selectedProcess = workProcessList.value.find(p => p.processName === taskName)
  if (selectedProcess) {
    taskList.value[index].taskCode = selectedProcess.processCode
    taskList.value[index].reportPermission = selectedProcess.workPermission || ''
    taskList.value[index].reportQtyRatio = selectedProcess.workRatio || 1
  }
}

// 产品高级选择相关方法
const handleAdvancedProductSelect = () => {
  productSelectDialogVisible.value = true
  fetchProductSelectList()
}

// 获取产品选择列表
const fetchProductSelectList = async () => {
  try {
    productSelectLoading.value = true
    const response = await getProducts()
    if (response.data.code === 200) {
      productSelectList.value = response.data.data || []
      productSelectPagination.totalCount = productSelectList.value.length
    }
  } catch (error) {
    console.error('获取产品选择列表失败:', error)
    ElMessage.error('获取产品列表失败')
  } finally {
    productSelectLoading.value = false
  }
}

// 产品搜索
const handleProductSearch = () => {
  productSelectPagination.pageIndex = 1
  fetchProductSelectList()
}

// 产品选择变化
const handleProductSelectionChange = (selection: Product[]) => {
  selectedProductRows.value = selection
}

// 产品选择分页大小变化
const handleProductSelectSizeChange = (size: number) => {
  productSelectPagination.pageSize = size
  productSelectPagination.pageIndex = 1
  fetchProductSelectList()
}

// 产品选择当前页变化
const handleProductSelectCurrentChange = (page: number) => {
  productSelectPagination.pageIndex = page
  fetchProductSelectList()
}

// 添加选中的产品
const handleAddSelectedProducts = () => {
  if (selectedProductRows.value.length === 0) {
    ElMessage.warning('请选择要添加的产品')
    return
  }
  
  // 这里可以根据需要处理选中的产品
  // 例如：将选中的产品添加到工单中
  const selectedProduct = selectedProductRows.value[0] // 取第一个选中的产品
  formData.productId = selectedProduct.productId
  formData.product = selectedProduct.productName
  formData.productCode = selectedProduct.productCode
  formData.productName = selectedProduct.productName
  formData.productSpec = selectedProduct.productSpec
  formData.unit = selectedProduct.inventoryUnit
  
  // 设置生产人员默认为创建人
  formData.producer = formData.creator || 'admin'
  
  // 启用产品相关字段（但仍然只读）
  enableProductFields()
  
  productSelectDialogVisible.value = false
  ElMessage.success('产品选择成功')
}

// 启用产品相关字段
const enableProductFields = () => {
  // 启用产品字段（但仍然保持只读状态）
  productFieldsDisabled.value = false
}

// 关闭产品选择弹出框
const handleProductSelectClose = () => {
  productSelectDialogVisible.value = false
  selectedProductRows.value = []
}

// 工序选择相关方法
const handleAddWorkProcess = () => {
  workProcessSelectDialogVisible.value = true
  fetchWorkProcessSelectList()
}

// 获取工序选择列表
const fetchWorkProcessSelectList = async () => {
  try {
    workProcessSelectLoading.value = true
    const response = await getWorkProcesses()
    if (response.data.code === 200) {
      workProcessSelectList.value = response.data.data || []
      workProcessSelectPagination.totalCount = workProcessSelectList.value.length
    }
  } catch (error) {
    console.error('获取工序选择列表失败:', error)
    ElMessage.error('获取工序列表失败')
  } finally {
    workProcessSelectLoading.value = false
  }
}

// 工序搜索
const handleWorkProcessSearch = () => {
  workProcessSelectPagination.pageIndex = 1
  fetchWorkProcessSelectList()
}

// 工序搜索重置
const handleWorkProcessReset = () => {
  workProcessSearchForm.processCode = ''
  workProcessSearchForm.processName = ''
  workProcessSelectPagination.pageIndex = 1
  fetchWorkProcessSelectList()
}

// 工序选择变化
const handleWorkProcessSelectionChange = (selection: WorkProcess[]) => {
  selectedWorkProcessRows.value = selection
}

// 工序选择分页大小变化
const handleWorkProcessSelectSizeChange = (size: number) => {
  workProcessSelectPagination.pageSize = size
  workProcessSelectPagination.pageIndex = 1
  fetchWorkProcessSelectList()
}

// 工序选择当前页变化
const handleWorkProcessSelectCurrentChange = (page: number) => {
  workProcessSelectPagination.pageIndex = page
  fetchWorkProcessSelectList()
}

// 添加选中的工序
const handleAddSelectedWorkProcesses = () => {
  if (selectedWorkProcessRows.value.length === 0) {
    ElMessage.warning('请选择要添加工序')
    return
  }
  
  // 将选中的工序添加到任务列表中
  selectedWorkProcessRows.value.forEach(workProcess => {
    const newTask: Task = {
      taskName: workProcess.processName,
      taskCode: workProcess.processCode,
      reportPermission: workProcess.workPermission || '',
      reportQtyRatio: workProcess.workRatio || 1,
      defectiveItemList: '', // 暂时为空，后续可以从工序管理中获取
      createTime: workProcess.createTime || '',
      creator: workProcess.creator || '',
      modifier: workProcess.modifier || '',
      modifyTime: workProcess.modifyTime || '',
      plannedStartTime: ''
    }
    taskList.value.push(newTask)
  })
  
  workProcessSelectDialogVisible.value = false
  selectedWorkProcessRows.value = []
  ElMessage.success(`成功添加 ${selectedWorkProcessRows.value.length} 个工序`)
}

// 关闭工序选择弹出框
const handleWorkProcessSelectClose = () => {
  workProcessSelectDialogVisible.value = false
  selectedWorkProcessRows.value = []
}

// 初始化数据
onMounted(() => {
  fetchWorkOrders()
  fetchProducts()
  fetchWorkProcesses()
})
</script>

<style scoped>
.work-order-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.work-order-section {
  background-color: white;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.section-header {
  padding: 16px 20px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-header h3 {
  margin: 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.search-action-bar {
  padding: 16px 20px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.search-area {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.table-container {
  padding: 0 20px 20px;
  height: calc(100vh - 300px);
  overflow-y: auto;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.pagination-container {
  padding: 16px 20px;
  border-top: 1px solid #e4e7ed;
  display: flex;
  justify-content: center;
}

:deep(.el-table) {
  border-radius: 4px;
}

:deep(.el-table__body-wrapper) {
  overflow-y: auto;
  max-height: calc(100vh - 400px);
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

.progress-display {
  display: flex;
  align-items: center;
  gap: 8px;
}

.progress-icon {
  color: #409eff;
  font-size: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

@media (max-width: 768px) {
  .search-action-bar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-area,
  .action-buttons {
    justify-content: center;
  }
}

/* 对话框样式 */
.dialog-content {
  max-height: 70vh;
  overflow-y: auto;
}

.basic-info-section {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
}

.basic-info-section h4 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.tasks-section {
  margin-top: 20px;
}

.tasks-section h4 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.task-actions {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.task-pagination {
  margin-top: 15px;
  display: flex;
  justify-content: center;
}

/* 对话框表格样式 */
:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #e4e7ed;
  padding: 20px;
}

:deep(.el-dialog__body) {
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #e4e7ed;
  padding: 15px 20px;
}

/* 产品选择弹出框样式 */
.product-select-container {
  padding: 20px 0;
}

.search-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.table-section {
  margin-bottom: 20px;
}

.pagination-section {
  margin-top: 20px;
  text-align: right;
}

/* 工序选择弹出框样式 */
.work-process-select-container {
  padding: 20px 0;
}

/* 只读字段样式 */
:deep(.el-input.is-disabled .el-input__wrapper) {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #606266;
}

:deep(.el-input.is-disabled .el-input__inner) {
  color: #606266;
  cursor: not-allowed;
}
</style>
